const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cookie: [],
    ss: [],
    list: [],
    h_h: "", //时
    m_m: "", //分
    s_s: "",   //秒
    time: "",    //倒计时
    timeArr: [],
    https: "https://csb2c.fenxiangqu.cn/",
    imgerror: 'nooo',   //缺失图片
    he: null, //滚动高度
    tab: "", //切换状态
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideLoading()
    try {
      var res = wx.getSystemInfoSync();
      this.setData({
        he: res.windowHeight + 'px'
      })

    } catch (e) {
      // Do something when catch error
      console.log(e)
    }
    var self = this;
    var a = wx.getStorageSync('cookie') || [];
    self.setData({
      cookie: a
    })
    wx.request({
      url: 'https://csb2c.fenxiangqu.cn/end_time',
      data: {
        a: ""
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + this.data.cookie
      },
      method: "POST",
      success: function (res) {
        var a = res.data.soon_activity;
        var aa = [];
        // now  进行    Future  即将    Past  结束
        for (var i = 0; i < a.length; i++) {
          aa.push({ _id: a[i]._id, name: a[i].name, state: "" })
          if (a[i].dateSection != "") {
            for (var j = 0; j < a[i].dateSection.length; j++) {
              var time1 = new Date().getTime();     //获取当前时间
              var early_morning = new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1).getTime();
              if (a[i].dateSection[j].startDateTime <= time1 && a[i].dateSection[j].endDateTime > time1) {
                aa[i].state = "now";
                self.detailsShop(aa[i]._id)
                //进行中
              } else if (a[i].dateSection[j].startDateTime < early_morning) {
                aa[i].state = "future";
                //即将开始
              } else if (a[i].dateSection[j].endDateTime < time1) {
                aa[i].state = "past";
                //已结束
              }
            }
          } else {
            const start = new Date(new Date(new Date().toLocaleDateString()).getTime());    //当前零点时间
            const end = new Date();       //当前时间
            const now = end - start;
            if (a[i].endTime < now) {
              aa[i].state = "past";
              //已结束
            } else if (a[i].startTime <= now && a[i].endTime > now) {
              aa[i].state = "now";
              self.detailsShop(aa[i]._id)
              //进行中
            } else {
              aa[i].state = "future";
              //即将开始
            }
          }
        }
        self.setData({
          ss: aa,
        })
      },
      fail: function (res) {
        wx.showToast({
          title: '网络故障啦！',
          icon: 'success',
          duration: 1000
        })
      },
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /*
  *加载限时商品
  */
  detailsShop: function (e) {
    var that = this;
    wx.request({
      url: 'https://csb2c.fenxiangqu.cn/panicbuy_id',
      data: {
        _id: e
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: "POST",
      success: function (res) {
        that.setData({
          tab: e,
          list: res.data.data,
          time: res.data.data[0][0].endTime,
        })
        that.countDown(); //执行倒计时
      },
      fail: function (res) {
        wx.showToast({
          title: '网络故障啦！',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },
  /*
  *小于10的格式化函数
  */
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  /** 
  * 倒计时函数
  */
  countDown: function () {
    var that = this;
    var obj = {}
    var countDownArr = [];

    var _nn = new Date();
    var nowTime =
      new Date(_nn.getFullYear() + "/" + (_nn.getMonth() + 1) + "/" + _nn.getDate()).getTime();
    var endTime = parseFloat(nowTime + this.data.time);
    var t2 = new Date(endTime);
    var t3 = new Date();
    var t = t2.getTime() - t3.getTime();
    var d = t2.getDate() - t3.getDate();
    var h = Math.floor(t / 1000 / 60 / 60 % 24);
    var m = Math.floor(t / 1000 / 60 % 60);
    var s = Math.floor(t / 1000 % 60);
    if (h < 0 || m < 0 || s < 0) {
      return false
    } else {
      obj = {
        hou: this.timeFormat(h),
        min: this.timeFormat(m),
        sec: this.timeFormat(s)
      }
    }
    countDownArr.push(obj);
    setTimeout(this.countDown, 1000);
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      timeArr: countDownArr
    })
  },
  /**
   * 切换
   */
  swich: function (e) {
    clearTimeout(this.countDown);  //清除定时器
    var id = e.currentTarget.dataset.id;
    this.detailsShop(id)
    this.setData({
      tab: id,
    })
  },
  /*
  * 限时限量加入购物车
  */
  show: function (e) {
    console.log(e)
    const self = this;
    const data = e.currentTarget.dataset;
    const id = data.id, xl = data.xl, jg = data.jg, activityid = data.activityid, types = data.type;
    
    if (+(jg) > 0.01 && jg !=""){
     
      wx.request({
        url: 'https://csb2c.fenxiangqu.cn/xcx_limited_buying_addShopCart_app',
        data: {
          xl:"1",
          id:id,
          activityID: activityid,
          type: types
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'Cookie': "LID=" + self.data.cookie
        },
        method: "POST",
        success: function (res) {
          console.log(res)
          if(res.data.state == 'login'){
            wx.showModal({
              title: '提示',
              content: '您未登录，是否前往登录？',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '../center/center',
                  })
                } else if (res.cancel) {
                  console.log('用户点击取消')
                  wx.navigateBack()
                }
              }
            })
          }else{
            if (res.data.state == "2") {
              wx.showToast({
                title: '添加成功！',
                icon: 'success',
                duration: 2000
              })
            } else if (res.data.state == "1") {
              wx.showToast({
                title: '库存不足',
                icon: 'success',
                duration: 2000
              })
            } else if (res.data.state == "3") {
              wx.showToast({
                title: '超出限制',
                icon: 'success',
                duration: 2000
              })
            } else if (res.data.state == "4") {
              wx.showToast({
                title: '活动过期',
                icon: 'success',
                duration: 2000
              })
            } else if (res.data.state == "5") {
              wx.showToast({
                title: '已存在',
                icon: 'success',
                duration: 2000
              })
            } else if (res.data.state == "0") {
              wx.showToast({
                title: '库存不足',
                icon: 'success',
                duration: 2000
              })
            } else {
              wx.showToast({
                title: '抢购失败',
                icon: 'success',
                duration: 2000
              })
            }
          }
        },
        fail: function (res) {
          wx.showToast({
            title: '网络故障啦！',
            icon: 'success',
            duration: 1000
          })
        }
      })
    }

  },
  /*
   *图片缺失 
   */
  imgError: function (e) {
    const m = e.currentTarget.dataset.m;
    const html = "list[" + m + "][1].sptm";
    console.log(this.data.imgerror)
    this.setData({
      [html]: this.data.imgerror
    })
  },
  /*
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})